package com.jamie.jvm.container;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 集合不安全的问题
 * ArrayList
 * @author Jmaie
 */
public class ContainerNotSafeDemo {

    public static void main(String[] args) {
        //        listNotSafe();
        //        setNotSafe();
        mapNotSafe();
    }

    private static void mapNotSafe() {
        //        Map<String, String> map = new HashMap<>(30);
        //        Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
        Map<String, String> map = new ConcurrentHashMap<>(30);
        for(int i = 0; i < 30; i++){
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }

    private static void setNotSafe() {
        //        listContainerNotSafe();
        //        Set<String> set = new HashSet<>();
        //        Set<String> set = Collections.synchronizedSet(new HashSet<>());
        Set<String> set = new CopyOnWriteArraySet<>();
        for(int i = 0; i < 30; i++){
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }

    private static void listNotSafe() {
        //        List<String> list = new ArrayList<>();
        //        List<String> list = new Vector<>();
        //        List<String> list = Collections.synchronizedList(new ArrayList<>());
        List<String> list = new CopyOnWriteArrayList<>();
        for(int i = 0; i < 30; i++){
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
        // java.util.ConcurrentModificationException 并发修改异常
        /**
         * 1.故障现象
         * java.util.ConcurrentModificationException
         * 2.导致原因
         *
         * 3.解决方案
         * 3.1 new Vector<>();
         * 3.2 Collections.synchronizedList(new ArrayList<>());
         * 3.3 new CopyOnWriteArrayList<>();
         * 4.优化建议(同样的错误不犯第2次)
         */

    }

}
